import React, { useRef, useEffect } from 'react'
import { Modal, Form, Input, message } from 'antd'
import { addConfigRequest, updateConfigRequest } from './ajax'
import { awaitWrap, confirmAction } from '@src/assets/js/tool'

const { Item } = Form

async function submitHandle (data, currentType, hide, refreshFn) {
  let fn = addConfigRequest
  const id = data.id
  if (id) {
    fn = updateConfigRequest
  } else {
    data.type = currentType.type
    data.updatebiz = currentType.updatebiz
  }
  if (!data.value) {
    data.value = data.title
  }
  const h = message.loading(id ? '更新中' : '添加中', 60)
  const [e] = await awaitWrap(fn(data))
  h()
  if (e) {
    return message.warning(e.message)
  }
  hide()
  refreshFn()
  message.success(id ? '更新成功' : '添加成功')
}

function confirmSubmit (d, currentType, hide, refreshFn) {
  if (currentType.updatebiz) {
    confirmAction('该修改会直接修改业务数据，是否确认同步修改？', () => submitHandle(d, currentType, hide, refreshFn))
  } else {
    submitHandle(d, currentType, hide, refreshFn)
  }
}

function Main ({ currentType, data, visible = false, hide = () => {}, refreshFn = () => {} }) {
  const formRef = useRef(null)
  useEffect(() => {
    const c = formRef.current
    if (c && data) {
      c.setFieldsValue(data)
    }
  }, [data, formRef])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c) {
      c.resetFields()
    }
  }, [visible])
  return (
    <div>
      <Modal
        title={data ? '修改配置项' : '添加配置项'}
        open={visible}
        onOk={() => {
          formRef.current.submit()
        }}
        onCancel={hide}
      >
        <Form ref={formRef} labelCol={{ flex: '80px' }} onFinish={(d) => { confirmSubmit(d, currentType, hide, refreshFn) }}>
          <Item name='id' noStyle><span /></Item>
          <Item name='type' noStyle><span /></Item>
          <Item name='title' label='名称' rules={[{ required: true, message: '名称不能为空' }]}>
            <Input placeholder='请输入' />
          </Item>
          {/* <Item name='value' label='值'>
            <Input placeholder='请输入' />
          </Item> */}
        </Form>
      </Modal>
    </div>
  )
}

export default Main
